package com.uduew.sjd.ui.mine

import android.net.Uri
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.api.GetFeedBackTypeApi
import com.uduew.sjd.api.SubmitFeedBackDcApi
import com.uduew.sjd.api.UploadFileApi
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.GetFeedBackTypeRequester
import com.uduew.sjd.request.ProductInfoRequester
import com.uduew.sjd.request.SubmitFeedBackDcRequester
import com.uduew.sjd.request.UploadFileRequester
import com.uduew.sjd.ui.adapter.GridImageAdapter
import com.uduew.sjd.ui.base.BaseFragment
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.utils.MainHandler
import com.uduew.sjd.utils.PhotoImagePicker
import com.uduew.sjd.utils.PhotoPickCallback
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.utils.Utils
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.smallmarker.tagflowlayout.TagFlowAdapter
import com.uduew.sjd.utils.ResUtil
import java.io.File
import java.io.IOException

class FeedbackFragment : BaseFragment() {

    lateinit var mState: SettingStates
    private lateinit var mProductInfoRequester: ProductInfoRequester
    private lateinit var mAdapter: GridImageAdapter
    private lateinit var mFlowAdapter: TagFlowAdapter<String?>
    private lateinit var mGetFeedBackTypeRequester: GetFeedBackTypeRequester
    private lateinit var mSubmitFeedBackDcRequester: SubmitFeedBackDcRequester
    private lateinit var mUploadFileRequester: UploadFileRequester

    override fun initViewModel() {
        mState = getFragmentScopeViewModel(SettingStates::class.java)
        mProductInfoRequester = getFragmentScopeViewModel(ProductInfoRequester::class.java)
        mGetFeedBackTypeRequester = getFragmentScopeViewModel(GetFeedBackTypeRequester::class.java)
        mSubmitFeedBackDcRequester =
            getFragmentScopeViewModel(SubmitFeedBackDcRequester::class.java)
        mUploadFileRequester = getFragmentScopeViewModel(UploadFileRequester::class.java)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        mUploadFileRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<HttpBean<UploadFileApi.UploadBean>> ->
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.data.let {
                if (it != null) {
                    mState.urlList.add(it.anaemia)
                    if (mState.imageList.isNotEmpty()) {
                        mState.imageList.removeAt(0)
                    }
                    if (mState.imageList.isNotEmpty()) {
                        val currentPhotoFile = mState.imageList[0]
                        mUploadFileRequester.request(this@FeedbackFragment, File(currentPhotoFile))
                    } else {
                        WaitDialog.show(getString(R.string.being_submitted))
                        var bean = SubmitFeedBackDcApi.ResSubmitFeedBackDcBean()
                        bean.setThorough(mState.feedContent.get())
                        bean.setEsculent(mState.beastlyListSelected)
                        bean.setOutgo(mState.urlList)
                        mSubmitFeedBackDcRequester.request(this@FeedbackFragment, bean)
                    }
                }
            }
        }

        mSubmitFeedBackDcRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<HttpBean<Any>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                TipDialog.show(getString(R.string.submission_successful))
                MainHandler.postDelay(1000) {
                    nav().navigateUp()
                }
            }
        }
        mGetFeedBackTypeRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<GetFeedBackTypeApi.ResGetFeedBackTypeBean> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                it?.hesitancy?.forEach { item ->
                    mState.tagList.add(item.giglot)
                    mState.beastlyList.add(item.beastly)
                }
                mFlowAdapter.notifyDataSetChange()
            }
        }
        mGetFeedBackTypeRequester.request(this)
        WaitDialog.show(getString(R.string.loading))
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        mFlowAdapter = TagFlowAdapter.create(mState.tagList) {
            setView { view, position, t ->
                TextView(requireContext()).apply {
                    text = t
                    setBackgroundResource(R.drawable.bg_tag_selector)
                    setPadding(30, 10, 30, 10)
                    setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12f)
                    setTextColor(ResUtil.getColor(R.color.tag_selector_color))
                }
            }
            setCheckedChanged { isChecked, position, view ->
                var mBeastly = mState.beastlyList[position]
                if (isChecked) {
                    if (!mState.beastlyListSelected.contains(mBeastly)) {
                        mState.beastlyListSelected.add(mBeastly)
                    }
                } else {
                    if (mState.beastlyListSelected.contains(mBeastly)) {
                        mState.beastlyListSelected.remove(mBeastly)
                    }
                }
                (view as TextView).setTextColor(
                    if (isChecked) {
                        ResUtil.getColor(R.color.white)
                    } else {
                        ResUtil.getColor(R.color.black)
                    }
                )
            }
        }

        mAdapter = GridImageAdapter(requireContext(), mState.fileList)
        mAdapter.selectMax = 5
        mAdapter.setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
            override fun onDelItemClick(v: View?, position: Int) {
                mState.imageNum.set(mAdapter.data.size)
            }

            override fun openPicture() {
                if (!Utils.checkDebounce()) return
                PhotoImagePicker.getInstance()
                    .startGallery(requireActivity(), object : PhotoPickCallback {
                        override fun onCanceled() {
                        }

                        override fun onPickImage(imageUri: Uri?) {
                            imageUri?.let { uri ->
                                try {
                                    var cacheFile = Utils.getFileFromUri(requireContext(), imageUri)
                                    mAdapter.append(cacheFile.absolutePath)
                                    mState.imageNum.set(mAdapter.data.size)
                                } catch (_: SecurityException) {
                                } catch (e: IOException) {
                                }
                            }
                        }
                    })
            }
        })
        return DataBindingConfig(R.layout.fragment_feed_back, BR.vm, mState)
            .addBindingParam(BR.adapter, mAdapter)
            .addBindingParam(BR.tagFlowAdapter, mFlowAdapter)
            .addBindingParam(BR.click, ClickProxy())
            .addBindingParam(BR.titleBarListener, TitleBarListener())
    }

    class SettingStates : StateHolder() {
        val text: State<String> = State("set")
        val fileList: MutableList<String?> = ArrayList<String?>()
        val imageList: MutableList<String?> = ArrayList<String?>()

        val urlList: ArrayList<String?> = ArrayList<String?>()
        val imageNum: State<Int> = State(0)
        val tagList: ArrayList<String?> = ArrayList<String?>()
        val beastlyList: ArrayList<String?> = ArrayList<String?>()
        val beastlyListSelected: ArrayList<String?> = ArrayList<String?>()
        val feedContent: State<String> = State("")
    }


    inner class TitleBarListener : OnTitleBarListener {
        override fun onLeftClick(titleBar: TitleBar?) {
            super.onLeftClick(titleBar)
            if (!Utils.checkDebounce()) return
            nav().popBackStack()
        }

        override fun onRightClick(titleBar: TitleBar?) {
            super.onRightClick(titleBar)
        }
    }

    open inner class ClickProxy {
        fun submit() {
            if (!Utils.checkDebounce()) return
            if (mState.beastlyListSelected.isEmpty()) {
                TipDialog.show(getString(R.string.please_select_the_feedback_type))
                return
            }
            mState.imageNum.get()?.let {
                if (it < 1) {
                    TipDialog.show(getString(R.string.please_select_the_screenshot))
                    return
                }
            }
            mState.feedContent.get()?.isNotBlank()?.let {
                if (!it) {
                    TipDialog.show(getString(R.string.please_enter_the_feedback_content))
                    return
                }
                WaitDialog.show(getString(R.string.loading))

                mState.imageList.addAll(mAdapter.data)
                if (mState.imageList.isNotEmpty()) {
                    val currentPhotoFile = mState.imageList[0]
                    mUploadFileRequester.request(this@FeedbackFragment, File(currentPhotoFile))
                }
            }
        }
    }

}